﻿namespace SharePointCSVImporter
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows;
    using System.Windows.Controls;

    using Microsoft.SharePoint.Client;

    public partial class FieldConfigurationPopup : ChildWindow
    {
        #region Fields

        public EventHandler NotifyFieldsReceived;

        private Configuration storedConfig;
        ListItemUpdater updater;
        private List<List> webLists;

        #endregion Fields

        #region Constructors

        public FieldConfigurationPopup(List<string> columnNames)
        {
            if (storedConfig == null)
            {
                storedConfig = new Configuration(columnNames);
            }
            else
            {
                storedConfig.CsvColumns = columnNames;
            }
            if (storedConfig.FieldMappings == null || storedConfig.FieldMappings.Count < 1)
            {
                GetFreshFieldMappings();
            }
            GetListsAndFieldsIfNeeded();
              //  if(storedConfig.)
            this.DataContext = storedConfig;
            this.Closing += FieldConfigurationPopup_Closing;
            InitializeComponent();
            SetActionVisibility();
        }

        public FieldConfigurationPopup()
        {
            InitializeComponent();
        }

        #endregion Constructors

        #region Properties

        public List<List> WebLists
        {
            get { return webLists; }
            set { webLists = value; }
        }

        internal Configuration StoredConfig
        {
            get { return storedConfig; }
            set { storedConfig = value; }
        }

        #endregion Properties

        #region Methods

        public void ClearMapping()
        {
        }

        internal void ReceiveFields(List<Field> fields)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                var o = this.LayoutRoot.Resources["listFieldOptions"];
                if (o != null)
                {
                    ListFields lf = o as ListFields;
                    lf.Fields = fields.Where(c => c.Hidden.Equals(false) && c.ReadOnlyField.Equals(false)).ToList();
                }
                storedConfig.BuildFieldMappings();
            });
        }

        internal void ReceiveWebLists(List<List> lists)
        {
            this.WebLists = lists;
            Dispatcher.BeginInvoke(delegate()
            {
                this.ListsComboBox.ItemsSource = lists;
            });
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void ClearMappingButton_Click(object sender, RoutedEventArgs e)
        {
            ConfigManager.ClearStorage();
            GetFreshFieldMappings();
        }

        private void ExportMappButton_Click(object sender, RoutedEventArgs e)
        {
            if (storedConfig != null)
            {
                ConfigurationImportExporter.ExportConfiguration(storedConfig);

            }
        }

        void FieldConfigurationPopup_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            storedConfig.Save();
            if (updater != null)
            {
                updater.Dispose();
            }
        }

        private void GetFreshFieldMappings()
        {
            if (storedConfig != null && storedConfig.CsvColumns != null)
            {
                if (storedConfig.FieldMappings != null)
                {
                    storedConfig.FieldMappings.Clear();
                }
                storedConfig.FieldMappings = CSVParser.CSVParser.GetFreshFieldMappings(storedConfig.CsvColumns);
            }
        }

        private void GetListsAndFieldsIfNeeded()
        {
            string targetWeb = storedConfig.TargetWebUrl;
            if (!string.IsNullOrEmpty(storedConfig.TargetWebUrl))
            {
                if (updater == null)
                {
                    updater = new ListItemUpdater(targetWeb);
                }
                updater.GetLists(ReceiveWebLists);
            }
            string targetList = storedConfig.TargetListName;
            if (!string.IsNullOrEmpty(targetList))
            {
                if (updater == null)
                {
                    updater = new ListItemUpdater(targetWeb);
                }
                updater.GetListFields(ReceiveFields, targetList);
            }
        }

        private void GetListsButton_Click(object sender, RoutedEventArgs e)
        {
            string targetWeb = storedConfig.TargetWebUrl;
            if (!string.IsNullOrEmpty(targetWeb))
            {

                updater = new ListItemUpdater(targetWeb);

                updater.GetLists(ReceiveWebLists);
            }
            else
            {
                MessageBox.Show("Provide Web Url");
            }
        }

        private void ImportMappButton_Click(object sender, RoutedEventArgs e)
        {
            var importer = new ConfigurationImportExporter();
            Configuration importedConfig = importer.ImportConfiguration();
            if (importedConfig != null)
            {
                this.StoredConfig = importedConfig;
                GetListsAndFieldsIfNeeded();
                this.DataContext = this.StoredConfig;
                this.StoredConfig.NotifyNewConfiguration();
            }
        }

        private void ListFieldCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            var data = cb.DataContext as CSVParser.FieldMapping;
            var selectedType = e.AddedItems[0].GetType();
            data.DestinationColumnType = selectedType.ToString();
        }

        private void MapButton_Click(object sender, RoutedEventArgs e)
        {
            string listName = storedConfig.TargetListName;
            if (!string.IsNullOrEmpty(listName))
            {
                if (updater == null)
                {
                    updater = new ListItemUpdater(storedConfig.TargetWebUrl);
                }
                updater.GetListFields(ReceiveFields, listName);
            }
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }

        private void OverWriteCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            this.ActionStackPanel.Visibility = System.Windows.Visibility.Visible;
        }

        private void OverWriteCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            this.ActionStackPanel.Visibility = System.Windows.Visibility.Collapsed;
        }

        void popTransform_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            storedConfig.Save();
            this.DataContext = this.StoredConfig;
            this.StoredConfig.NotifyNewConfiguration();
        }

        private void SetActionVisibility()
        {
            if (storedConfig.OverwriteExistingValues)
            {
                this.ActionStackPanel.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                this.ActionStackPanel.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void TransformRecordButton_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;

            CSVParser.FieldMapping mapping = btn.DataContext as CSVParser.FieldMapping;
            ColumnRulesPopup pop = new ColumnRulesPopup(ref mapping, storedConfig.FieldMappings);
            pop.Closing += popTransform_Closing;
            pop.Show();
        }

        #endregion Methods
    }
}